#include "decimator.h"

#include <QtQml>

Decimator::Decimator(QObject *parent) : QObject(parent)
{
}

void Decimator::registerTypes(const char *uri)
{
    qmlRegisterType<Decimator>(uri, 1, 0, "Decimator");
}

bool Decimator::init(int downFactor,int inBurstLength)
{
    __downFactor = downFactor;
    __maxBurstLength = inBurstLength;
    input = new ISignal(1, inBurstLength);
    output = new DecimationOSignal(this,1);

    return true;
}

ISignal * Decimator::getInputSignal()
{
    return input;
}

OSignal * Decimator::getOutputSignal()
{
    return output;
}

bool Decimator::DecimationOSignal::onBurstRequest(size_t outBurstLength)
{
    ISignal &input = *(contextPtr->input);
    int maxBurstLength = contextPtr->__maxBurstLength;
    int numSamples = outBurstLength * contextPtr->__downFactor;
    Buffer<sample_t> buffer(numSamples);
    buffer.clear();

    if (numSamples > maxBurstLength)
    {
        int div = numSamples/maxBurstLength;
        int mod = numSamples % maxBurstLength;

        for (int i = 0 ; i < div ; i++)
        {
            input.requestBurst(maxBurstLength);
            for (int j = 0 ; j < maxBurstLength ; j++)
            {
                input.readInSample();
                buffer[i*maxBurstLength + j] = input[0];
            }
        }
        input.requestBurst(mod);
        for (int j = 0 ; j < mod ; j++)
        {
            input.readInSample();
            buffer[div*maxBurstLength + j] = input[0];
        }
    }
    else
    {
        input.requestBurst(numSamples);
        for (int i = 0 ; i < numSamples ; i++)
        {
            input.readInSample();
            buffer[i] = input[0];
        }
    }
    for (int i = 0; i < numSamples ; i+= contextPtr->__downFactor)
    {
        (*this)[0] = buffer[i];
        this->writeOutSample();
    }
    return true;
}
